package com.farm.common.security;

import cn.hutool.core.util.ArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collection;

@Component("pms")
public class PermissionAccess {

    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;

    /**
     * 判断接口是否有任意xxx，xxx权限
     * @param permissions 权限
     * @return {boolean}
     */
    public boolean hasPermission(String... permissions){
        // return true;
        // 校验权限
        // 如果无需校验权限，可直接返回 true
         if (ArrayUtil.isEmpty(permissions)) {
             return false;
         }
         if (Arrays.asList(permissions).contains("ROLE_CUSTOM")){
             return true;
         }

         Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
         if (authentication == null) {
             return false;
         }
         if (Arrays.stream(permissions).anyMatch(x -> x.equals("ROLE_ADMIN") || x.equals("VIEW_LOGIN"))){
             return authentication.isAuthenticated();
         }
         Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
         boolean hasPermission = authorities.stream().map(GrantedAuthority::getAuthority).filter(StringUtils::hasText)
                 .anyMatch(x -> PatternMatchUtils.simpleMatch(permissions, x));
         return hasPermission;
    }

}
